//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.example.starterdemo.demo;

import com.alibaba.fastjson.JSON;
import com.example.starterdemo.demo.dto.ApiResultDto;
import com.example.starterdemo.demo.util.EncryptUtil;
import com.example.starterdemo.demo.util.HttpUtil;
import com.example.starterdemo.demo.util.SliceIdGenerator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class WeblfasrDemo {
    public static final String LFASR_HOST = "http://raasr.xfyun.cn/api";
    public static final String APPID = "";
    public static final String SECRET_KEY = "";
    public static final String PREPARE = "/prepare";
    public static final String UPLOAD = "/upload";
    public static final String MERGE = "/merge";
    public static final String GET_RESULT = "/getResult";
    public static final String GET_PROGRESS = "/getProgress";
    public static final int SLICE_SICE = 10485760;

    public WeblfasrDemo() {
    }

    public static void main(String[] args) {
        File audio = new File("D:\\project\\demo\\starter-demo\\src\\main\\resources\\audio\\lfasr.wav");

        try {
            Throwable var2 = null;
            Object var3 = null;

            try {
                FileInputStream fis = new FileInputStream(audio);

                try {
                    String taskId = prepare(audio);
                    byte[] slice = new byte[10485760];

                    int len;
                    for(SliceIdGenerator generator = new SliceIdGenerator(); (len = fis.read(slice)) > 0; uploadSlice(taskId, generator.getNextSliceId(), slice)) {
                        if (fis.available() == 0) {
                            slice = Arrays.copyOfRange(slice, 0, len);
                        }
                    }

                    merge(taskId);

                    while(true) {
                        try {
                            System.out.println("sleep a while Zzz");
                            Thread.sleep(20000L);
                        } catch (InterruptedException var23) {
                            var23.printStackTrace();
                        }

                        ApiResultDto taskProgress = getProgress(taskId);
                        if (taskProgress.getOk() == 0) {
                            if (taskProgress.getErr_no() != 0) {
                                System.out.println("任务失败：" + JSON.toJSONString(taskProgress));
                            }

                            String taskStatus = taskProgress.getData();
                            if (JSON.parseObject(taskStatus).getInteger("status") == 9) {
                                System.out.println("任务完成！");
                                System.out.println("\r\n\r\n转写结果: " + getResult(taskId));
                                break;
                            }

                            System.out.println("任务处理中：" + taskStatus);
                        } else {
                            System.out.println("获取任务进度失败！");
                        }
                    }
                } finally {
                    if (fis != null) {
                        fis.close();
                    }

                }
            } catch (Throwable var25) {
                if (var2 == null) {
                    var2 = var25;
                } else if (var2 != var25) {
                    var2.addSuppressed(var25);
                }

                throw var2;
            }
        } catch (SignatureException var26) {
            var26.printStackTrace();
        } catch (FileNotFoundException var27) {
            var27.printStackTrace();
        } catch (Throwable var28) {
            var28.printStackTrace();
        }

    }

    public static Map<String, String> getBaseAuthParam(String taskId) throws SignatureException {
        Map<String, String> baseParam = new HashMap();
        String ts = String.valueOf(System.currentTimeMillis() / 1000L);
        baseParam.put("app_id", "8da4f9ac");
        baseParam.put("ts", ts);
        baseParam.put("signa", EncryptUtil.HmacSHA1Encrypt(EncryptUtil.MD5(ts), "c086f552876327638378a06cbbe5a6e4"));
        if (taskId != null) {
            baseParam.put("task_id", taskId);
        }

        return baseParam;
    }

    public static String prepare(File audio) throws SignatureException {
        Map<String, String> prepareParam = getBaseAuthParam((String)null);
        long fileLenth = audio.length();
        prepareParam.put("file_len", String.valueOf(fileLenth));
        prepareParam.put("file_name", audio.getName());
        prepareParam.put("slice_num", String.valueOf(fileLenth / 10485760L + (long)(fileLenth % 10485760L == 0L ? 0 : 1)));
        String response = HttpUtil.post("http://raasr.xfyun.cn/api/prepare", prepareParam);
        if (response == null) {
            throw new RuntimeException("预处理接口请求失败！");
        } else {
            ApiResultDto resultDto = (ApiResultDto)JSON.parseObject(response, ApiResultDto.class);
            String taskId = resultDto.getData();
            if (resultDto.getOk() == 0 && taskId != null) {
                System.out.println("预处理成功, taskid：" + taskId);
                return taskId;
            } else {
                throw new RuntimeException("预处理失败！" + response);
            }
        }
    }

    public static void uploadSlice(String taskId, String sliceId, byte[] slice) throws SignatureException {
        Map<String, String> uploadParam = getBaseAuthParam(taskId);
        uploadParam.put("slice_id", sliceId);
        String response = HttpUtil.postMulti("http://raasr.xfyun.cn/api/upload", uploadParam, slice);
        if (response == null) {
            throw new RuntimeException("分片上传接口请求失败！");
        } else if (JSON.parseObject(response).getInteger("ok") == 0) {
            System.out.println("分片上传成功, sliceId: " + sliceId + ", sliceLen: " + slice.length);
        } else {
            System.out.println("params: " + JSON.toJSONString(uploadParam));
            throw new RuntimeException("分片上传失败！" + response + "|" + taskId);
        }
    }

    public static void merge(String taskId) throws SignatureException {
        String response = HttpUtil.post("http://raasr.xfyun.cn/api/merge", getBaseAuthParam(taskId));
        if (response == null) {
            throw new RuntimeException("文件合并接口请求失败！");
        } else if (JSON.parseObject(response).getInteger("ok") == 0) {
            System.out.println("文件合并成功, taskId: " + taskId);
        } else {
            throw new RuntimeException("文件合并失败！" + response);
        }
    }

    public static ApiResultDto getProgress(String taskId) throws SignatureException {
        String response = HttpUtil.post("http://raasr.xfyun.cn/api/getProgress", getBaseAuthParam(taskId));
        if (response == null) {
            throw new RuntimeException("获取任务进度接口请求失败！");
        } else {
            return (ApiResultDto)JSON.parseObject(response, ApiResultDto.class);
        }
    }

    public static String getResult(String taskId) throws SignatureException {
        String responseStr = HttpUtil.post("http://raasr.xfyun.cn/api/getResult", getBaseAuthParam(taskId));
        if (responseStr == null) {
            throw new RuntimeException("获取结果接口请求失败！");
        } else {
            ApiResultDto response = (ApiResultDto)JSON.parseObject(responseStr, ApiResultDto.class);
            if (response.getOk() != 0) {
                throw new RuntimeException("获取结果失败！" + responseStr);
            } else {
                return response.getData();
            }
        }
    }
}
